package com.artlongs.base.controller;

import com.artlongs.base.JodaDateEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    /**
     * 初始化共同的req,res给子类使用
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
    }

    /**
     * SPRING MVC 让人很无奈的类型初始化注册
     * 这个方法本应当应用于扩展类别的注册的，结果基本的类型也要注册一下，很无语:(
     * @param binder
     */
    @InitBinder
    private void dateBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new JodaDateEditor());
    }

    /**
     * 对BindingResult 进行基本的封装以方便检查前端输入的格式的错误信息
     * @param result
     * @return
     */
    protected List<String> getErrorMessageListFromBindingResult(BindingResult result) {
        List<String> errorMsgList = new ArrayList<String>();
        for(ObjectError error : result.getAllErrors()) {
            errorMsgList.add(error.getDefaultMessage());
        }
        return errorMsgList;
    }


    protected String redirectTo( String url ) {
        StringBuffer rto = new StringBuffer("redirect:");
        rto.append(url);
        return rto.toString();
    }

}
